package com.hoshiibuy.fileServer.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.hoshiibuy.fileServer.model.ResizePictureRequest;
import com.hoshiibuy.fileServer.model.UploadFileRepsonse;
import com.hoshiibuy.fileServer.model.UploadFileRequest;
import com.hoshiibuy.fileServer.model.UploadFilesRequest;
import com.hoshiibuy.fileServer.model.UploadFilesResponse;
import com.hoshiibuy.fileServer.result.Result;
import com.hoshiibuy.fileServer.service.FileObjectService;
import com.hoshiibuy.fileServer.util.ObsPictureProcessUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping("/file")
@Api(tags = "文件操作接口")
public class FileObjectController {
	@Autowired
	private FileObjectService fileObjectService;

	@RequestMapping(value = "/uploadOneFile", method = RequestMethod.POST)
	@ApiOperation(value = "上传一个文件", notes = "传入已存在objectKey时将会覆盖原文件")
	public Result uploadOneFile(UploadFileRequest param, MultipartFile file) throws Exception {
		if (file == null || file.getSize() == 0) {
			return Result.wrap500Error("文件为空");
		}
		String bucketName = param.getBucketName();
		String objectKey = param.getObjectKey();
		String folder = param.getFolder();
		InputStream fileInputStream = file.getInputStream();
		if (StringUtils.isBlank(objectKey)) {
			objectKey = DigestUtils.md5DigestAsHex(fileInputStream);
		}
		Result<String> uploadResult = fileObjectService.uploadFile(bucketName, folder, objectKey, fileInputStream);
		UploadFileRepsonse info = new UploadFileRepsonse(uploadResult.getStatus());
		if (uploadResult.isSuccess()) {
			info.setUrl(uploadResult.getData());
		}
		info.setFileName(param.getFileName());
		info.setObjectKey(objectKey);
		return Result.wrapSuccess(info);
	}

	@RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
	@ApiOperation(value = "上传多个文件", notes = "文件信息列表内不需传入bucketName，传入已存在objectKey时将会覆盖原文件", consumes = "multipart/form-data")
	public Result uploadFiles(UploadFilesRequest param, MultipartFile[] files) {
		if (files == null || files.length == 0) {
			return Result.wrap500Error("文件列表为空");
		}

		List<UploadFileRepsonse> uploadFileInfoList = new ArrayList<UploadFileRepsonse>();
		int successCount = 0;
		// 指定的存储空间名称
		String bucketName = param.getBucketName();
		List<UploadFileRequest> fileList = param.getFileInfoList();
		for (MultipartFile file : files) {

			if (file.isEmpty()) {
				UploadFileRepsonse info = new UploadFileRepsonse(Result.STATUS_500, "文件为空");
				info.setFileName(file.getOriginalFilename());
				uploadFileInfoList.add(info);
			} else {
				String objectKey = null;
				String folder = param.getFolder();
				InputStream fileInputStream = null;
				try {
					fileInputStream = file.getInputStream();

					// 查找参数里文件的objectKey,如没有找到则用文件md5
					for (UploadFileRequest uploadFileRequest : fileList) {
						if (file.getOriginalFilename().equals(uploadFileRequest.getFileName())) {
							objectKey = uploadFileRequest.getObjectKey();
						}
					}
					if (StringUtils.isBlank(objectKey)) {
						objectKey = DigestUtils.md5DigestAsHex(fileInputStream);
					}

					Result<String> uploadResult = fileObjectService.uploadFile(bucketName, folder, objectKey,
							fileInputStream);

					UploadFileRepsonse info = new UploadFileRepsonse(uploadResult.getStatus());
					if (uploadResult.isSuccess()) {
						// 上传成功返回对象url和objectKey
						info.setUrl(uploadResult.getData());
						info.setObjectKey(objectKey);
						successCount++;
					}
					info.setFileName(file.getOriginalFilename());
					uploadFileInfoList.add(info);

				} catch (IOException e) {
					UploadFileRepsonse info = new UploadFileRepsonse(Result.STATUS_500, "文件IO异常");
					info.setFileName(file.getOriginalFilename());
					uploadFileInfoList.add(info);
				} catch (Exception e) {
					UploadFileRepsonse info = new UploadFileRepsonse(Result.STATUS_500, "上传服务异常");
					info.setFileName(file.getOriginalFilename());
					uploadFileInfoList.add(info);
				}
			}
		}
		UploadFilesResponse response = new UploadFilesResponse();
		response.setSuccessCount(successCount);
		response.setUploadCount(files.length);
		response.setFileInfoList(uploadFileInfoList);
		Result<UploadFilesResponse> result = Result.wrapSuccess(response);
		return result;
	}

	@RequestMapping(value = "/resizePic", method = RequestMethod.POST)
	@ApiOperation(value = "对图片进行缩放，转换格式，压缩处理")
	public Result resizePicture(ResizePictureRequest param) {
		// 判断url是否为图片文件路径
		if (!ObsPictureProcessUtil.isImg(param.getImgUrl())) {
			return Result.wrap500Error("不支持的图片路径");
		}
		// 判断转换格式是否支持
		if (StringUtils.isNotBlank(param.getTargetFormat())) {
			String tempFormat = "." + param.getTargetFormat();
			if (ObsPictureProcessUtil.isValid(tempFormat, ObsPictureProcessUtil.allowPicTypes)) {
				return Result.wrap500Error("不支持的图片格式");
			}
		}

		String imgUrl = param.getImgUrl();
		// 追加华为云操作前缀
		imgUrl += "?x-image-process=";
		imgUrl = ObsPictureProcessUtil.resize(imgUrl, param.getWidth(), param.getHeight());
		imgUrl = ObsPictureProcessUtil.compQuality(imgUrl, param.getQuality());

		if (StringUtils.isNotBlank(param.getTargetFormat())) {
			imgUrl = ObsPictureProcessUtil.formatTransform(imgUrl, param.getTargetFormat());
		}
		Result<String> result = Result.wrapSuccess(imgUrl);
		return result;

	}

	@RequestMapping("/test")
	@ApiIgnore
	public Result test() {
		return fileObjectService.test();

	}

}
